import requests
import json
import os
import jwtgen

def get_weather(locid):
    url = "https://p96hewpw9q.re.qweatherapi.com/v7/weather/now"
    params = {"location": locid}  # 默认位置代码，可根据需要修改
    token = jwtgen.gen_jwt()
    headers = {
        "Authorization": f"Bearer {token}",
        "Accept-Encoding": "gzip",  # 添加压缩支持
    }

    try:
        # 添加超时参数：连接超时5秒，读取超时10秒
        response = requests.get(url, headers=headers, params=params, timeout=(5, 10))

        if response.status_code == 200:
            # print("天气请求成功！")
            weather_data = response.json()
            # 这里可以添加对返回数据的处理逻辑
            return weather_data
        else:
            print(f"请求失败，状态码: {response.status_code}")
            print("错误信息:", response.text)
            return {}

    except requests.exceptions.Timeout:
        print("请求超时：服务器响应时间过长")
        return {}
    except requests.exceptions.RequestException as e:
        print("请求发生错误:", e)
        return {}


def get_forecast_weather(locid):
    url = "https://p96hewpw9q.re.qweatherapi.com/v7/weather/3d"
    params = {"location": locid}  # 默认位置代码，可根据需要修改
    token = jwtgen.gen_jwt()
    headers = {
        "Authorization": f"Bearer {token}",
        "Accept-Encoding": "gzip",  # 添加压缩支持
    }

    try:
        # 添加超时参数：连接超时5秒，读取超时10秒
        response = requests.get(url, headers=headers, params=params, timeout=(5, 10))

        if response.status_code == 200:
            weather_data = response.json()
            return weather_data
        else:
            print(f"请求失败，状态码: {response.status_code}")
            print("错误信息:", response.text)
            return {}

    except requests.exceptions.Timeout:
        print("请求超时：服务器响应时间过长")
        return {}
    except requests.exceptions.RequestException as e:
        print("请求发生错误:", e)
        return {}


if __name__ == "__main__":
    print(get_forecast_weather(101020400)["daily"][0]['textDay'])

